/* ===========================================================
 * 二次封装模态窗
 * bootstrap-modal.js v2.2.5
 * bootstrap-modalmanager.js v2.2.5
 * ===========================================================
 * Copyright(c) 2012-2020 YGSoft.Inc
 * Created by wugang5 on 2016/5/12.
 */
define(["jquery","bs-modal", "ecp.utils.i18n"], function($, $modal, $locale){
	(function($){
	    $.fn.bsWindow = function(options) {
	        var defaults = {
	            title: $locale.Control.sDefaultTitle,
	            content: '',
	            url: '', //远程URL
	            width: '',//自定义窗体宽度
	            multilayer: false, //允许多层嵌套窗体
	            showCloseButton: true, //显示关闭按钮
	            fade: true,//是否有动画效果
	            isTip:false, //标准的提示窗
	            detailedMessage:'', //详细信息
	            isHtml:false,  //是否html片段
				offClick:false, //是否卸载自动关闭模态框事件
	            otherButtons: [], //其他按钮文本，样式默认,["确定","取消"]
	            otherButtonStyles: [], //其他按钮的样式，['btn-primary','btn-primary'],bootstrap按钮样式
	            bootstrapModalOption: {}, //默认的bootstrap模态对话框参数
	            dialogShow: function() {}, //对话框即将显示事件
	            dialogShown: function() {}, //对话框已经显示事件
	            dialogHide: function() {}, //对话框即将关闭
	            dialogHidden: function() {}, //对话框已经关闭事件
	            clickButton: function (sender, modal, index, callback) {} //选中按钮的序号，排除关闭按钮。sender:按钮jquery对象，model:对话框jquery对象,index:按钮的顺序,otherButtons的数组下标
	        };

	        var options = $.extend(defaults, options);
	        var modalID = '';
	        //生成一个惟一的ID
	        function getModalID() {
	            var d = new Date();
	            var vYear = d.getFullYear();
	            var vMon = d.getMonth() + 1;
	            var vDay = d.getDate();
	            var h = d.getHours();
	            var m = d.getMinutes();
	            var se = d.getSeconds();
	            var sse = d.getMilliseconds();
	            return 't_' + vYear + vMon + vDay + h + m + se + sse;
	        }
	   
	  
	        $.fn.extend({
	            closeDialog: function(modal) {
	                var modalObj = modal;
	                modalObj.modal('hide');
	            }
	        });
	        
	        
	        return this.each(function () {
	            var $this = $(this);
	            modalID = getModalID();
	            $this.attr("data-target", modalID);
	            var tmpHtml = '<div tabindex="-1" id="{ID}" class="colorModal modal ';
	            if (options.fade) {
	                tmpHtml = tmpHtml + 'fade';
	            }
	            if (options.multilayer) {
	                tmpHtml = tmpHtml + '" data-focus-on="input:first';
	            }
	            if(options.isTip){
	                tmpHtml = tmpHtml + '" data-width="400px"';
	            }else{
	                tmpHtml = tmpHtml + '" data-width='+ options.width || "";
	            }
	            tmpHtml = tmpHtml + '><div id="head_{ID}" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
	            + '<h4 class="modal-title" id="myModalLabel_{ID}">{title}</h4></div><div class="modal-body" id="body_{ID}"';
	            if(options.isTip){
	            	tmpHtml = tmpHtml + 'style="min-height:77px;padding:29px 15px;"';
	            }
	            tmpHtml = tmpHtml + '>{body}</div><div class="modal-footer">{button}</div></div>';
	            var buttonHtml = '<button id="closeBtn_{ID}" class="btn" data-dismiss="modal" aria-hidden="true">'+$locale.Control.sClose+'</button>';
	            if (!options.showCloseButton && options.otherButtons.length > 0) {
	                buttonHtml = '';
	            }
	            ;
	            //生成按钮
	            var btnClass = 'cls-' + modalID;
	            for (var i = 0; i < options.otherButtons.length; i++) {
	            	 buttonHtml += '<button buttonIndex="' + i + '" class="' + btnClass + ' btn ' + options.otherButtonStyles[i] + '">' + options.otherButtons[i] + '</button>';
	            }

	            if(options.isTip && options.detailedMessage !== ""){
	            	buttonHtml = '<span id="showOrHide_{ID}" style="float:left;margin-top:8px"><i class="fa fa-angle-down"></i>&nbsp;'+$locale.Control.showDetail+'</span>' + buttonHtml ;
	                if(options.isHtml){
	                    buttonHtml = buttonHtml + '<div id="detailMsg_{ID}"  style="overflow: auto;min-height:100px;text-align:left;padding:8px;max-height: 400px;margin-top: 20px; display: none ; '
	                                            + 'border:1px solid #cecece;border-radius:6px;"></div> ';
	                } else {
	                    buttonHtml = buttonHtml + '<textarea id="detailMsg_{ID}" class="form-control" readonly rows="3" style="overflow:auto; max-height:400px;margin-top: 20px; display: none"></textarea>';
	                }
	            }
	            tmpHtml = tmpHtml.replace(/{title}/g, options.title).replace(/{body}/g, '').replace(/{button}/g, buttonHtml).replace(/{ID}/g, modalID);
	            $this.append(tmpHtml);

	            var $showOrHide = $("#showOrHide_"+ modalID);
	            if($showOrHide && $showOrHide.length){
	                $showOrHide.bind('click', function(){
	                    var $this = $(this),
	                        $detailMsg = $("#detailMsg_" + modalID);
	                    if(options.isTip){
	                        options.isTip = false;
	                        $this.empty().html('<i class="fa fa-angle-up"></i>&nbsp;'+$locale.Control.hideDetail);
	                        $detailMsg.css("display","block");
	                        options.isHtml ? $detailMsg.html(options.detailedMessage) : $detailMsg.val(options.detailedMessage);
	                    } else {
	                        options.isTip = true;
							$this.empty().html('<i class="fa fa-angle-down"></i>&nbsp;'+$locale.Control.showDetail);
	                        $detailMsg.css("display","none");
	                    }
	                })
	            }
				
				/**
				*按钮触发事件后触发提示
				*/
				function notify(msg,timer){
					$("#head_"+modalID).prepend('<div id="saveMsg" class="inner-alert">'+msg+'</div>');
					var $saveMsg = $("#saveMsg"),
						left = -($saveMsg[0].offsetWidth)/2;
					$saveMsg.css("margin-left", left);
					var startTime = new Date().getTime(),
						delayTime = timer || 5000,
						endTime,
						time =setTimeout(function(){
							$saveMsg.remove();
						},delayTime);
					$saveMsg.mouseover(function(){
						//清除定时器
						clearTimeout(time);
						endTime = new Date().getTime();
					}).mouseout(function(){
						setTimeout(function(){
							$saveMsg.remove();
							//计算剩余时间
						},delayTime - endTime + startTime);
					});
				}
				
	            //只有一个关闭按钮时
	            if(options.showCloseButton && !options.otherButtons.length){
	                $("#closeBtn_"+modalID).addClass("btn-primary");
	            }
				
	            var modalObj = $('#' + modalID);
	            //绑定按钮事件,不包括关闭按钮
	            $('.' + btnClass).click(function() {
	                var index = $(this).attr('buttonIndex');
	                options.clickButton($(this),modalObj,index,notify);
	            });

	            modalObj.on('show' , function(){
	                //此处改为同步，否则会影响模态窗定位
	                if (options.url != '') {
	                    $.ajax({
	                        type: "get",
	                        async: false,
	                        cache: true,
	                        url: options.url,
	                        data: "dialogModalId=" + modalID + "&ajaxloader=ajax-loader",
	                        success: function(data) {
	                            $('#body_' + modalID).html(data);
	                        },
	                        error: function(e) {
	                            $('#body_' + modalID).html($locale.Control.sLoadError);
	                        }
	                    });
	                } else {
	                    $('#body_' + modalID).html(options.content);
	                }
	                options.dialogShow();
	            });
	            modalObj.on('shown', function(){
	                //只有一个关闭按钮时，处理焦点 
	                if (options.showCloseButton && !options.otherButtons.length) {
	                    $("#closeBtn_"+modalID).focus();
	                };
	                options.dialogShown();
					if(options.offClick){
						$(".modal-scrollable").off('click.modal');
					}
	            })
	            modalObj.on('hide', function(){
	                options.dialogHide();
	            });
	            modalObj.on('hidden', function(){
	                options.dialogHidden();
	                $this.removeAttr("data-target");
	                modalObj.remove();
	            })
	            modalObj.modal(options.bootstrapModalOption);
	        });
	    }
	    $.extend({
	        bsWindow: function(options) {
	            $("body").bsWindow(options);
	        }
	    })
	})(window.jQuery);
	
	return {
		bsWindow : $.bsWindow
	}
});